package com.ruoyi.thread;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.HttpClient;
import com.ruoyi.common.config.FileStorageProperties;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.domain.pojo.FilePO;
import com.ruoyi.mapper.FileMapper;
import com.ruoyi.utils.AudioUtil;
import com.ruoyi.utils.WordToHtml;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.UUID;

import static com.ruoyi.utils.DocxGenerator.createDocx;

/**
 * @Classname processThread
 * @Description TODO
 * @Date 2025/3/24 10:23
 * @Created by xxx
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class processThread implements Runnable {
    private FilePO filePO;
    private FileMapper fileMapper;
    private FileStorageProperties fileStorageProperties;
    private UUID uuid;
    private String baseUrl;

    @Override
    public void run() {
        Integer type = filePO.getType();
        String filePath = filePO.getFilePath();

        if (Objects.equals(type, Constants.AUDIO)) {
            handleAudioFile(filePath);
        } else if (Objects.equals(type, Constants.TEXT)) {
            handleTextFile(filePath);
        }

        // 处理生成纪要部分
        JSONObject result = null;
        JSONObject request = new JSONObject();
        String base64 = AudioUtil.fileToBase64(filePath);
        String format = filePath.substring(filePath.lastIndexOf(".") + 1);
        request.put("file_base64", base64);
        request.put("format", format);
        request.put("docx_title", filePO.getTitle());
        addTimeParams(request);

        String url = fileStorageProperties.getGenUrl();
        try {
            result = JSON.parseObject(HttpClient.doPostJson(url, request));
        } catch (Exception e) {
            minutesError(e);
            return;
        }
        processResult(result);
    }

    private void handleAudioFile(String filePath) {
        String fileString = AudioUtil.fileToBase64(filePath);
        String format = filePath.substring(filePath.lastIndexOf(".") + 1);
        JSONObject request = new JSONObject();
        request.put("file_string", fileString);
        request.put("format", format);
        JSONObject result = null;
        filePO.setUpdateTime(LocalDateTime.now());
        try {
            String ans = HttpClient.doPostJson(fileStorageProperties.getTransUrl(), request);
            result = JSON.parseObject(ans);
        } catch (Exception e) {
            transError(e);
            return;
        }

        if (result == null || !"0".equals(result.getString("code"))) {
            transError(new Exception(result != null ? result.getString("msg") : "查询失败"));
            return;
        }

        String transResult = result.getString("result");
        Path transPath = Paths.get(fileStorageProperties.getUploadDir(), filePO.getCreateBy().toString(), Constants.TRANS_DIR, uuid.toString() + ".docx");

        createDocx(transPath, transResult); // 使用新方法创建 .docx 文件

        filePO.setTransPath(transPath.toString());
        filePO.setStatus(1);
        filePO.setContent(transResult);
        fileMapper.update(filePO);
    }

    private void handleTextFile(String filePath) {
        File file = new File(filePath);
        String content = "";
        try {
            content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8);
            if (!filePath.endsWith(".txt")) {
                content = WordToHtml.wordToHtml(filePath, false);
            }
        } catch (IOException e) {
            fileError(e);
            return;
        } catch (Exception ignored) {
            fileError(new Exception("文件错误"));
            return;
        }
        filePO.setStatus(0);
        filePO.setContent(content);
        fileMapper.update(filePO);
    }

    private void processResult(JSONObject result) {
        log.info("查询结果：{}", result);
        if (result == null || !"0".equals(result.getString("code"))) {
            minutesError(new Exception(result != null ? result.getString("msg") : "查询失败"));
            return;
        }

        String base64Result = result.getString("result_docx_base64");
        String think = result.getString("think");
        Path minutesPath = Paths.get(fileStorageProperties.getUploadDir(), filePO.getCreateBy().toString(), Constants.MINUTES_DIR, uuid.toString() + ".docx");
        try {
            if (!Files.exists(minutesPath.getParent())) Files.createDirectories(minutesPath.getParent());
            String minutes = "生成完毕";
            createDocx(minutesPath, minutes);
            WordToHtml.base64ToFile(base64Result, minutesPath.toString());
            filePO.setSummary(think);
            filePO.setMinutesPath(minutesPath.toString());
            filePO.setStatus(2);
            filePO.setMinutes(minutes);
            fileMapper.update(filePO);
            log.info("保存文件成功：{}", minutesPath);
        } catch (Exception e) {
            minutesError(e);
            return;
        }
    }

    private void addTimeParams(JSONObject request) {
        String startTime = filePO.getStartTime();
        if (startTime != null && !startTime.isEmpty()) {
            request.put("date_Y", startTime.substring(0, 4));
            request.put("open_date_M", startTime.substring(5, 7));
            request.put("date_M", startTime.substring(5, 7));
            if (!startTime.startsWith("00", 8)) {
                request.put("open_date_D", startTime.substring(8, 10));
                request.put("date_D", startTime.substring(8, 10));
            }
        }
    }


    private void minutesError(Exception e) {
        log.error("纪要请求失败：{}", e.getMessage());
        String minutes = "纪要内容暂无";
        Path minutesPath = Paths.get(fileStorageProperties.getUploadDir(), filePO.getCreateBy().toString(), Constants.MINUTES_DIR, uuid.toString() + ".docx");
        createDocx(minutesPath, minutes); // 使用新方法创建 .docx 文件
        filePO.setSummary("思考过程暂无");
        filePO.setMinutesPath(minutesPath.toString());
        filePO.setMinutes(minutes);
        filePO.setStatus(-2);
        filePO.setReason("请求失败");
        fileMapper.update(filePO);
    }

    private void fileError(Exception e) {
        log.error("获取文件内容失败：{}", e.getMessage());
        String minutes = "纪要内容暂无";
        Path minutesPath = Paths.get(fileStorageProperties.getUploadDir(), filePO.getCreateBy().toString(), Constants.MINUTES_DIR, uuid.toString() + ".docx");
        createDocx(minutesPath, minutes); // 使用新方法创建 .docx 文件
        filePO.setSummary("思考过程暂无");
        filePO.setMinutesPath(minutesPath.toString());
        filePO.setContent("获取内容为空");
        filePO.setMinutes(minutes);
        filePO.setStatus(-2);
        filePO.setReason("获取文件内容失败");
        fileMapper.update(filePO);
    }

    private void transError(Exception e) {
        log.error("请求失败：{}", e.getMessage());
        String trans = "转写内容暂无";
        Path transPath = Paths.get(fileStorageProperties.getUploadDir(), filePO.getCreateBy().toString(), Constants.TRANS_DIR, uuid.toString() + ".docx");
        String minutes = "纪要内容暂无";
        Path minutesPath = Paths.get(fileStorageProperties.getUploadDir(), filePO.getCreateBy().toString(), Constants.MINUTES_DIR, uuid.toString() + ".docx");
        createDocx(transPath, trans); // 使用新方法创建 .docx 文件
        createDocx(minutesPath, minutes); // 使用新方法创建 .docx 文件
        filePO.setSummary("思考过程暂无");
        filePO.setTransPath(transPath.toString());
        filePO.setMinutesPath(minutesPath.toString());
        filePO.setStatus(-1);
        filePO.setContent(trans);
        filePO.setMinutes(minutes);
        filePO.setReason("请求失败");
        fileMapper.update(filePO);
    }
}
